package com.ellecity06.cwhiskymall.ui.home.good

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseViewModel
import com.ellecity06.cwhiskymall.bean.request.GoodRequest
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/24 19:25
 * @des
 */
class GoodViewModel : BaseViewModel() {
    //创建意图管道，容量无限大
    val intentChannel = Channel<GoodIntent>(Channel.UNLIMITED)

    var mState = MutableStateFlow<GoodState?>(null)
    val state = mState.asStateFlow()

    init {
        viewModelScope.launch {
            //收集意图
            intentChannel.consumeAsFlow().collect {
                collectIntent(it)

            }
        }
    }

    fun reset() {
        mState = MutableStateFlow<GoodState?>(null)
    }

    suspend fun collectIntent(it: GoodIntent) {
        when (it) {
            is GoodIntent.Goods -> {
                if (!it.isLoad) {
                    pagerHelper.pageIndex = 1
                }
                fetchGoods(it)
            }
        }
    }

    private fun fetchGoods(it: GoodIntent.Goods) {
        val request = GoodRequest(specialSubjectId = it.id)
        request.pageNum = pagerHelper.pageIndex
        request.pageSize = 10
        request(api = { specialGoods(request) }, success = {

            if (it?.records != null) {
                if (pagerHelper.pageIndex == 1) {
                    val hasMore = it?.records.size >= request.pageSize
                    mState.value = GoodState.RefreshGoods(it.records, hasMore)
                } else {
                    val hasMore = it?.records.size >= request.pageSize
                    mState.value = GoodState.LoadMoreGoods(it.records, hasMore)
                }
                pagerHelper.pageIndex++
            }

        })
    }

    override fun onCleared() {
        super.onCleared()

    }
}